import datetime
import os
import random

from alipay import AliPay
from mydjango import settings

# 获取文件路径
app_private_key_path = os.path.join(settings.BASE_DIR, "apps/goods/keys/app_private_key.pem")
alipay_public_key_path = os.path.join(settings.BASE_DIR, "apps/goods/keys/alipay_public_key.pem")

with open(app_private_key_path) as f:
    app_private_key_string = f.read()

with open(alipay_public_key_path) as f:
    alipay_public_key_string = f.read()

# print(app_private_key_string)
# print(alipay_public_key_string)

# 创建支付宝支付对象
alipay = AliPay(
    appid=settings.ALIPAY_APPID,
    app_notify_url=None,  # 默认回调url
    app_private_key_string=app_private_key_string,
    alipay_public_key_string=alipay_public_key_string,
    sign_type="RSA2",
    debug=settings.ALIPAY_DEBUG
)


def get_pay_url(out_trade_no, total_amount, subject):
    # 生成登录支付宝连接
    order_string = alipay.api_alipay_trade_page_pay(
        out_trade_no=out_trade_no,
        total_amount=str(total_amount),
        subject=subject,
        return_url=settings.ALIPAY_RETURN_URL,
    )

    # 响应登录支付宝连接
    # 真实环境电脑网站支付网关：https://openapi.alipay.com/gateway.do? + order_string
    # 沙箱环境电脑网站支付网关：https://openapi.alipaydev.com/gateway.do? + order_string
    alipay_url = settings.ALIPAY_URL + "?" + order_string
    return alipay_url

def get_order_id():

    """
    SYL202008241212121200005/24
    生成订单号: 格式: SYL + 年月日时分秒 + 5位随机数
    :return:
    """
    d = datetime.datetime.now()
    base = 'SYL'
    time_str = '%04d%02d%02d%02d%02d%02d' % (d.year, d.month, d.day, d.hour, d.minute,d.second)
    rand_num = str(random.randint(10000, 99999))
    return base + time_str + rand_num